<?php
/**
 * Created by PhpStorm.
 * User: ezy
 * Date: 2019-11-25
 * Time: 16:09
 */

namespace Reezy\OAuth\Driver;

use Reezy\AlipaySdk\AlipaySdk;
use Reezy\OAuth\OAuthBase;
use Reezy\OAuth\OAuthInfo;

class OAuthAlipay extends OAuthBase
{
    const AUTHORIZE_URL = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm';

    /**
     * @var  AlipaySdk
     */
    protected $sdk;

    protected $scope = 'auth_base';


    public function __construct(array $config)
    {
        parent::__construct($config);

        $this->sdk = AlipaySdk::create($this->clientId, $this->clientSecret)->useCerts($config['app_cert_path'], $config['root_cert_path'], $config['alipay_cert_path']);
    }

    public function getCodeKey(): string
    {
        return 'auth_code';
    }

    public function isSupportSilentMode(): bool
    {
        return $this->scope === 'auth_base';
    }

    public function getAuthUrl(string $redirectUri = null, string $state = null, bool $isSilent = false): string
    {
        return self::buildUrl(self::AUTHORIZE_URL, [
            'app_id' => $this->clientId,
            'redirect_uri' => $redirectUri ?? $this->redirectUri,
            'scope' => $isSilent ? 'auth_base' : 'auth_user',
            'state' => $state,
            'response_type' => 'code',
        ]);
    }

    public function getAccessToken($code): OAuthInfo
    {
        $body = $this->sdk->execute('alipay.system.oauth.token', [
            'grant_type' => 'authorization_code',
            'code' => $code,
        ]);
        return OAuthInfo::token($body);
    }

    public function getUserInfo(OAuthInfo $token): OAuthInfo
    {
        $info = $this->sdk->execute('alipay.user.info.share', [
            'auth_token' => $token->getAccessToken()
        ]);

        return OAuthInfo::userinfo($info, 'nick_name', 'avatar');
    }
}
